 
import { request } from "../../request/index"
import { showModal,chooseAddress,showToast } from "../../utils/tools"
import regeneratorRuntime, { awrap } from '../../lib/runtime/runtime';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 详情数据
    goodsDeatil:[],
    isCollent:false
  },
  // 详情数据 
  goodsDeatil:[],
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) { 
    let goods_id = options.goods_id 
    this.goodsDeatil(goods_id)
    let coll =wx.getStorageSync('coll') 
    // 页面加载判断 本地缓存得  收藏数据  如果存在 isCollent = true
    let index = coll.findIndex( (v,i) => v.goods_id == goods_id)
    if(index != -1){
      this.setData({
        isCollent:true
      })
    }else{
      this.setData({
        isCollent:false
      })
    } 

 
  },

  // 获取商品详情
  async goodsDeatil(goods_id){ 
     let res = await request({url:"/goods/detail",data:{goods_id}})   
     this.goodsDeatil =  res 
     this.setData({
       goodsDeatil:{
          goods_id:res.goods_id,
          cat_id:res.goods_name, 
          goods_name:res.goods_name,
          goods_price:res.goods_price,
          goods_introduce:res.goods_introduce.replace(/\.webp/g,'.jpg'),
          pics:res.pics
       }
     })
  },

  // 轮播图 预览
  handleprevewImage(e){ 
    let current = e.currentTarget.dataset.url
    // urls 图片数组
    const urls = this.goodsDeatil.pics.map(v=>v.pics_mid_url)
    wx.previewImage({
      current, // 当前显示图片的http链接
      urls // 需要预览的图片http链接列表
    })
  },

  // 加入购物车
  handleCartAdd(){
    let cart = wx.getStorageSync('cart') || []  
    let index = cart.findIndex(v=>v.goods_id == this.goodsDeatil.goods_id)    
    if(index == -1){ // 没数据
      this.goodsDeatil.num = 1
      this.goodsDeatil.checked = true
      cart.push(this.goodsDeatil)
    }else{ // 有数据
      cart[index].num++
    }
    wx.setStorageSync('cart', cart)
    wx.showToast({
      title: '加入成功',
   })   
 
  },

  // 收藏
  async clickCollent(){ 
    let {isCollent,goodsDeatil} = this.data 
    isCollent = !isCollent  
    let Collent = wx.getStorageSync('coll') || []  
    let index = Collent.findIndex( (v,i)=> v.goods_id == goodsDeatil.goods_id )   
    // return 
    if( index != -1 ){  
      // 已收藏
      Collent.splice(index,1)  
      await showToast({title:"取消收藏",duration:1000})
    }else{
      // 没有收藏
      Collent.push(goodsDeatil)  
      await showToast({title:"成功收藏", duration:1000 })  
    }
    wx.setStorageSync('coll', Collent)
    // 存回去
    this.setData({
      isCollent
    })
  }
})